source('codes/00_import_libraries.R')


#-----------------------------------------------------------------------------#
# data ------------------------------------------------------------------------
#-----------------------------------------------------------------------------#

crisis = readRDS('input/uncertainty_and_crisis_indexes.rds')

dt = readRDS('input/combined_data.rds')[['base']] %>% 
  select(ym, War, contains('mkt')) %>% 
  mutate(across(contains('mkt'), ~ .x*12)) %>% 
  inner_join(crisis, by = 'ym') |> 
  drop_na(CWar)



#-----------------------------------------------------------------------------#
# function --------------------------------------------------------------------
#-----------------------------------------------------------------------------#

fn_res = function(x_list, beg_yr, h) {
  
  mod_list = lapply(x_list, function(x) {
    fn_fit_ols(
      df   = dt %>% filter(year(ym) >= beg_yr), 
      xvar = x, 
      yvar = paste0('mkt', h)
    )
  })
  
  mod_robust = lapply(mod_list, function(mod) {
    coeftest(mod, vcov. = NeweyWest(mod, lag = 6, prewhite = F))
  })
  
  r2 = lapply(mod_list, function(mod) glance(mod)$adj.r.squared * 100) %>%
    unlist()
  
  out = huxreg(
    mod_robust
    , coefs        = x_list[[length(x_list)]]
    , error_format = "({statistic})"
    , stars        = c(`***` = 0.01, `**` = 0.05, `*` = 0.1)
    , statistics   = c(0)
    , borders      = 0
    , outer_borders= 0
    , note         = NULL
  )
  
  rbind(out[-1, ], c('$R^2$', r2))  
}



#-----------------------------------------------------------------------------#
# apply -----------------------------------------------------------------------
#-----------------------------------------------------------------------------#

panel_list = c('1918-2018', '1950-2018', '2000:2018')
x_list = list('War', 'Crisis', 'CWar', c('War', 'Crisis', 'CWar'))


out = lapply(c(1900, 1950, 2000), function(y) {
  fn_res(x_list = x_list, beg_yr = y, h = 1)
})


output = lapply(seq_along(out), function(i) {
  out[[i]] %>% 
    insert_row(panel_list[i], fill = '') %>% 
    merge_across(1, everywhere) %>% 
    set_align(1, everywhere, 'center') %>% 
    set_number_format(1, everywhere, 0) %>% 
    set_number_format(-1, -1, 2) %>% 
    set_tb_borders(1, everywhere, 0.8) %>% 
    set_bottom_border(final(1), everywhere, 0.8)
}) %>% 
  do.call(what = rbind) %>% 
  as_hux() %>% 
  set_all_padding(0) %>% 
  set_escape_contents(F)

quick_xlsx(output, file = glue('output/tables/Table_6B.xlsx'))




